#![no_std]
#![no_main]

/// 嵌入式系统演示 - 展示Rust在嵌入式开发中的优势
/// 包括：no_std环境、内存管理、硬件抽象、实时系统

use core::panic::PanicInfo;
use core::sync::atomic::{AtomicU32, Ordering};

// 模拟硬件寄存器
static mut LED_REGISTER: u32 = 0;
static mut UART_DATA: u32 = 0;
static mut TIMER_COUNTER: AtomicU32 = AtomicU32::new(0);

// 系统状态
static mut SYSTEM_STATE: SystemState = SystemState {
    led_state: false,
    uart_enabled: false,
    timer_enabled: false,
    error_count: 0,
};

#[derive(Debug, Clone, Copy)]
struct SystemState {
    led_state: bool,
    uart_enabled: bool,
    timer_enabled: bool,
    error_count: u32,
}

// 硬件抽象层 (HAL)
mod hal {
    use super::*;
    
    /// GPIO控制
    pub struct Gpio {
        port: u32,
        pin: u32,
    }
    
    impl Gpio {
        pub fn new(port: u32, pin: u32) -> Self {
            Self { port, pin }
        }
        
        pub fn set_high(&self) {
            unsafe {
                LED_REGISTER |= 1 << (self.port * 8 + self.pin);
            }
        }
        
        pub fn set_low(&self) {
            unsafe {
                LED_REGISTER &= !(1 << (self.port * 8 + self.pin));
            }
        }
        
        pub fn toggle(&self) {
            unsafe {
                LED_REGISTER ^= 1 << (self.port * 8 + self.pin);
            }
        }
        
        pub fn read(&self) -> bool {
            unsafe {
                (LED_REGISTER & (1 << (self.port * 8 + self.pin))) != 0
            }
        }
    }
    
    /// UART通信
    pub struct Uart {
        baud_rate: u32,
    }
    
    impl Uart {
        pub fn new(baud_rate: u32) -> Self {
            Self { baud_rate }
        }
        
        pub fn write_byte(&self, byte: u8) -> Result<(), &'static str> {
            unsafe {
                UART_DATA = byte as u32;
            }
            Ok(())
        }
        
        pub fn read_byte(&self) -> Option<u8> {
            unsafe {
                if UART_DATA != 0 {
                    let byte = UART_DATA as u8;
                    UART_DATA = 0;
                    Some(byte)
                } else {
                    None
                }
            }
        }
        
        pub fn write_string(&self, s: &str) -> Result<(), &'static str> {
            for byte in s.bytes() {
                self.write_byte(byte)?;
            }
            Ok(())
        }
    }
    
    /// 定时器
    pub struct Timer {
        frequency: u32,
        enabled: bool,
    }
    
    impl Timer {
        pub fn new(frequency: u32) -> Self {
            Self {
                frequency,
                enabled: false,
            }
        }
        
        pub fn start(&mut self) {
            self.enabled = true;
            unsafe {
                SYSTEM_STATE.timer_enabled = true;
            }
        }
        
        pub fn stop(&mut self) {
            self.enabled = false;
            unsafe {
                SYSTEM_STATE.timer_enabled = false;
            }
        }
        
        pub fn get_counter(&self) -> u32 {
            unsafe {
                TIMER_COUNTER.load(Ordering::Relaxed)
            }
        }
    }
    
    /// ADC (模数转换器)
    pub struct Adc {
        channel: u8,
        resolution: u8,
    }
    
    impl Adc {
        pub fn new(channel: u8, resolution: u8) -> Self {
            Self { channel, resolution }
        }
        
        pub fn read(&self) -> u16 {
            // 模拟ADC读取
            unsafe {
                let raw_value = TIMER_COUNTER.load(Ordering::Relaxed) % 4096;
                raw_value as u16
            }
        }
        
        pub fn read_voltage(&self, reference_voltage: f32) -> f32 {
            let raw = self.read();
            let max_value = (1 << self.resolution) - 1;
            (raw as f32 / max_value as f32) * reference_voltage
        }
    }
}

// 传感器数据处理
mod sensors {
    use super::*;
    
    /// 温度传感器
    pub struct TemperatureSensor {
        adc: hal::Adc,
        calibration_offset: f32,
        calibration_scale: f32,
    }
    
    impl TemperatureSensor {
        pub fn new(channel: u8) -> Self {
            Self {
                adc: hal::Adc::new(channel, 12),
                calibration_offset: 0.0,
                calibration_scale: 1.0,
            }
        }
        
        pub fn read_temperature(&self) -> f32 {
            let voltage = self.adc.read_voltage(3.3);
            // 模拟温度转换公式
            (voltage - self.calibration_offset) * self.calibration_scale * 100.0
        }
    }
    
    /// 压力传感器
    pub struct PressureSensor {
        adc: hal::Adc,
        zero_offset: f32,
        sensitivity: f32,
    }
    
    impl PressureSensor {
        pub fn new(channel: u8) -> Self {
            Self {
                adc: hal::Adc::new(channel, 12),
                zero_offset: 0.0,
                sensitivity: 1.0,
            }
        }
        
        pub fn read_pressure(&self) -> f32 {
            let voltage = self.adc.read_voltage(3.3);
            (voltage - self.zero_offset) * self.sensitivity
        }
    }
}

// 通信协议
mod protocol {
    use super::*;
    
    /// 简单的通信协议
    pub struct Protocol {
        uart: hal::Uart,
        buffer: [u8; 64],
        buffer_index: usize,
    }
    
    impl Protocol {
        pub fn new() -> Self {
            Self {
                uart: hal::Uart::new(9600),
                buffer: [0; 64],
                buffer_index: 0,
            }
        }
        
        pub fn send_command(&mut self, command: &str) -> Result<(), &'static str> {
            self.uart.write_string("CMD:")?;
            self.uart.write_string(command)?;
            self.uart.write_string("\r\n")?;
            Ok(())
        }
        
        pub fn process_received_data(&mut self) -> Option<&str> {
            if let Some(byte) = self.uart.read_byte() {
                if byte == b'\n' || byte == b'\r' {
                    if self.buffer_index > 0 {
                        self.buffer[self.buffer_index] = 0;
                        self.buffer_index = 0;
                        return Some(core::str::from_utf8(&self.buffer[..self.buffer_index]).unwrap_or(""));
                    }
                } else if self.buffer_index < self.buffer.len() - 1 {
                    self.buffer[self.buffer_index] = byte;
                    self.buffer_index += 1;
                }
            }
            None
        }
    }
}

// 主应用程序
struct EmbeddedApp {
    led: hal::Gpio,
    uart: hal::Uart,
    timer: hal::Timer,
    temperature_sensor: sensors::TemperatureSensor,
    pressure_sensor: sensors::PressureSensor,
    protocol: protocol::Protocol,
}

impl EmbeddedApp {
    fn new() -> Self {
        Self {
            led: hal::Gpio::new(0, 0),
            uart: hal::Uart::new(9600),
            timer: hal::Timer::new(1000),
            temperature_sensor: sensors::TemperatureSensor::new(0),
            pressure_sensor: sensors::PressureSensor::new(1),
            protocol: protocol::Protocol::new(),
        }
    }
    
    fn initialize(&mut self) {
        // 初始化硬件
        self.timer.start();
    }
    
    fn run(&mut self) -> ! {
        // 主循环
        loop {
            // 处理通信协议
            let command = self.protocol.process_received_data();
            if let Some(cmd) = command {
                // 将命令处理逻辑内联，避免借用冲突
                match cmd {
                    "LED_ON" => self.led.set_high(),
                    "LED_OFF" => self.led.set_low(),
                    "LED_TOGGLE" => self.led.toggle(),
                    "TEMP" => {
                        let _temp = self.temperature_sensor.read_temperature();
                        let _ = self.protocol.send_command("TEMP:25.5");
                    },
                    "PRESSURE" => {
                        let _pressure = self.pressure_sensor.read_pressure();
                        let _ = self.protocol.send_command("PRESSURE:1013.25");
                    },
                    "STATUS" => {
                        let _status = unsafe { SYSTEM_STATE };
                        let _ = self.protocol.send_command("STATUS:LED=true,ERRORS=0");
                    },
                    _ => {
                        let _ = self.protocol.send_command("ERROR:UNKNOWN_COMMAND");
                    }
                }
            }
            
            // 简单的延时
            self.delay(1000);
        }
    }
    
    
    fn delay(&self, cycles: u32) {
        for _ in 0..cycles {
            core::hint::spin_loop();
        }
    }
}

// 入口点
#[no_mangle]
pub extern "C" fn main() -> ! {
    let mut app = EmbeddedApp::new();
    app.initialize();
    app.run();
}

// 恐慌处理
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    // 在嵌入式系统中，恐慌处理通常包括：
    // 1. 记录错误信息
    // 2. 重置系统
    // 3. 进入安全模式
    
    unsafe {
        // 点亮错误LED
        LED_REGISTER |= 0x80000000;
    }
    
    loop {
        // 无限循环，等待看门狗复位
        core::hint::spin_loop();
    }
}